<?php
/**
 * Created by PhpStorm.
 * User: allen
 * Date: 2019/3/8
 * Time: 12:48
 */

namespace app\admin\model;

use app\admin\validate\Lottery;
use think\Model;

class ArticleLog extends Model
{
    protected $createTime = true;
    protected $pk='id';

    /**
     * 检测
     * @param int $aid
     * @param int $mid
     * @param int $mc_id
     * @return bool
     */
    public function check($aid=0,$mid=0,$mc_id=0){
        $res = $this
            ->where('mc_id','eq',$mc_id)
            ->where('mid','eq',$mid)
            ->where('aid','eq',$aid)
            ->count();
        return $res?true:false;
    }

    /**
     * 添加分享记录
     * @param $mid
     * @param $aid
     * @param $mc_id
     * @param string $out
     * @return bool
     */
    public function addLog($mid,$aid,$mc_id,&$out=''){
        $validate = new \app\index\validate\ArticleLog();
        $data = [
            'mid'=>$mid,
            'aid'=>$aid,
            'mc_id'=>$mc_id,
            'create_time'=>time(),
        ];
        if(!$validate->check($data)){
            $out = $validate->getError();
            return false;
        }
        if(!$this->insert($data)){
            return false;
        }
        return true;
    }

    /**
     * @param array $where
     * @param int $pageSize
     * @param string $field
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($where= [], $pageSize=10,$field='*'){
        $list = $this
            ->field($field)
            ->with([
                'article',
                'member',
                'mch'
            ])
            ->order('create_time desc')
            ->where($where)
            ->paginate($pageSize);
        return $list;
    }

    public function article(){
        return $this->hasOne('article','id','aid')
            ->bind([
                'title',
                'description',
                'image',
            ]);
    }
    public function member(){
        return $this->hasOne('member','id','mid')
            ->bind([
                'username',
                'nickname'
            ]);
    }
    public function mch(){
        return $this->hasOne('mch','id','mc_id')
            ->bind([
                'name',
                'tel'
            ]);
    }

    /**
     * 邀请人数
     * @param int $form_id
     * @param int $aid
     * @param int $mc_id
     * @return float|string
     */
    public function sums($form_id=0,$aid=0,$mc_id=0){
        return $this
            ->where('form_id','eq',$form_id)
            ->where('aid','eq',$aid)
            ->where('mc_id','eq',$mc_id)
            ->count('id');
    }

}